package net.zigin.nhi.waste.net;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class TokenInterceptor implements Interceptor {
    private HashMap<String,String> urlParams=new HashMap<>();
    private HashMap<String,String> headers=new HashMap<>();


    public HashMap<String, String> getUrlParams() {
        return urlParams;
    }

    public void setUrlParams(HashMap<String, String> urlParams) {
        this.urlParams = urlParams;
    }

    public HashMap<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(HashMap<String, String> headers) {
        this.headers = headers;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        HttpUrl.Builder authorizedUrlBuilder = request.url()
                .newBuilder();
        if (urlParams!=null){
            for (Map.Entry<String, String> entry : urlParams.entrySet()) {
                authorizedUrlBuilder.addQueryParameter(entry.getKey(),entry.getValue());
            }
        }

        Request.Builder builder = request.newBuilder()
                .method(request.method(), request.body())
                .url(authorizedUrlBuilder.build())
                //对所有请求添加请求头
                .header("mobileFlag", "android");
        if (headers!=null){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.addHeader(entry.getKey(),entry.getValue());
            }
        }

        Request newRequest = builder.build();
        return chain.proceed(newRequest);
    }
}
